package com.neuedu.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.neudeu.util.ResultHandler;
import com.neudeu.util.SqlQueryUpdate;
import com.neuedu.dao.IUserDAO;
import com.neuedu.entity.UserEntity;

public class UserDAOImpl implements IUserDAO{

	@Override
	public List<UserEntity> selectAll() {
		String sql="select * from usertable";
		return SqlQueryUpdate.query(sql, new ResultHandler<UserEntity>() {

			@Override
			public UserEntity getResult(ResultSet rs) throws SQLException {
				UserEntity user=new UserEntity();
				user.setUid(rs.getInt("uid"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("upwd"));
				user.setUtelephone(rs.getString("utelephone"));
				user.setUaddress(rs.getString("uaddress"));
				return user;
			}
		});
	}

	@Override
	public int insert(UserEntity user) {
		String sql="insert into usertable (uname,upwd,utelephone,uaddress) values(?,?,?,?)";
		int i=SqlQueryUpdate.update(sql, user.getUname(),user.getUpwd(),user.getUtelephone(),user.getUaddress());
		return i;
	}

	@Override
	public int delete(int id) {
		String sql="delete from usertable where uid=?";
		int i=SqlQueryUpdate.update(sql, id);
		return i;
	}

	@Override
	public UserEntity find(int id) {
		String sql="select * from usertable where uid=?";
		List<UserEntity> listuser= SqlQueryUpdate.query(sql, new ResultHandler<UserEntity>() {

			@Override
			public UserEntity getResult(ResultSet rs) throws SQLException {
				UserEntity user=new UserEntity();
				user.setUid(rs.getInt("uid"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("upwd"));
				user.setUtelephone(rs.getString("utelephone"));
				user.setUaddress(rs.getString("uaddress"));
				return user;
			}
		},id);
		if(listuser.size()==0) {
			return null;
		}
		return  listuser.get(0);
	}

	@Override
	public int update(UserEntity user) {
		String sql="update usertable set uname=?,upwd=?,utelephone=?,uaddress=? where uid=?";
		int i=SqlQueryUpdate.update(sql, user.getUname(),user.getUpwd(),user.getUtelephone(),user.getUaddress(),user.getUid());
		return i;
	}

	@Override
	public UserEntity login(String uname, String upwd) {
		String sql="select * from usertable where uname=? and upwd=?";
		List<UserEntity> listuser= SqlQueryUpdate.query(sql, new ResultHandler<UserEntity>() {

			@Override
			public UserEntity getResult(ResultSet rs) throws SQLException {
				UserEntity user=new UserEntity();
				user.setUid(rs.getInt("uid"));
				user.setUname(rs.getString("uname"));
				user.setUpwd(rs.getString("upwd"));
				user.setUtelephone(rs.getString("utelephone"));
				user.setUaddress(rs.getString("uaddress"));
				return user;
			}
		},uname,upwd);
		if(listuser==null ||listuser.size()==0) {
			return null;
		}
		return  listuser.get(0);
	}

}
